﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common.Result
{
    public class CommonResultFilter : IAsyncResultFilter
    {
        public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            // 1、实现统一包装
            if (context.Result is ObjectResult objectResult)
            {
                int? StatusCode = objectResult.StatusCode;
                if (StatusCode == 200
                    || StatusCode == 201
                    || StatusCode == 202
                    || !StatusCode.HasValue)
                {
                    // 1、统一包装正常结果 (单个数据或者集合数据)
                    objectResult.Value = WrapSuccessResult(objectResult.Value);
                }
                /*else
                {
                    // 2、包装异常结果
                    objectResult.Value = WrapFailResult(objectResult);
                }*/
            }
            await next();
        }

        // 1、判断数据的类型然后统一包装。
        private object WrapSuccessResult(object value)
        {
            // 1、创建统一结果
            CommonResult commonResult = new CommonResult();
            commonResult.ErrorNo = "0";

            // 2、获取结果(输出到页面：结果集List<>)
            if (value.GetType().Name.Contains("List"))
            {
                // 转换成List结果输出
                commonResult.Result = new JsonResult(value).Value;
            }
            else if (value.GetType().Name.Contains("CommonResult"))
            {
                return value;
            }
            else
            {
                // 转换为单个结果输出
                commonResult.Result = new JsonResult(value).Value;
            }
            return commonResult;
        }
    }
}
